package org.gunncs.tests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;

import org.gunncs.RobotModel;
import org.gunncs.ui.DashBoardComponent;

public class Main {

	/**
	 * @param args
	 */
	public static boolean running;
	
	public static void main(String[] args) {
        JFrame viewer = new JFrame("Dashboard");
        viewer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DashBoardComponent board = new DashBoardComponent(new RobotModel());
        viewer.add(board);
        viewer.setSize(800, 500);
      
        viewer.setVisible(true);
        viewer.repaint();
        Socket sock = null;
        BufferedReader in = null;
        running = true;
        try {
			sock = new Socket("127.0.0.1", 8080);
			 in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

        double i=0;
        while(running){
        	/*i = System.currentTimeMillis();
        	//Randomize Data for each Sensor;
        	board.getRobotModel().getSensors().elementAt(0).setState(
        			"" + (Math.random()>.5? 1.0 : 0.0) + ";"  + (Math.random()>.5? 1.0 : 0.0) +";" +i);

        	board.getRobotModel().getSensors().elementAt(1).setState(
        			"" + (Math.random()*250) + ";" +i);
        	board.getRobotModel().getSensors().elementAt(2).setState(
        			"" + (Math.random()*250) + ";" +i);
        	board.getRobotModel().getSensors().elementAt(3).setState(
        			"" + (Math.random()*90) + ";" +i);
        	board.getRobotModel().getSensors().elementAt(5).setState(
        			"" + (Math.random()*-90) + ";" +i);
        	board.getRobotModel().getSensors().elementAt(4).setState(
        			"" + (Math.random()*250) + ";" +i);
        	board.getRobotModel().getSensors().elementAt(6).setState(
        			"" + (Math.random()>.5? 1.0 : 0.0) + ";"  
        			+ (Math.random()>.5? 1.0 : 0.0) +";" 
        			+ (Math.random()>.5? 1.0 : 0.0) +";" +i);
        	board.getRobotModel().getSensors().elementAt(7).setState(
        			"" + (Math.random()*360) + ";" +i);
        	try {
        		viewer.repaint();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
        	String s="";
			try {
				s = in.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
        	if(!s.equals("")){
        		System.out.println(s);
        		try{
        			board.getRobotModel().updateStatus(s.split("\t"));
        		}catch(Exception e){		}
        	}
        	try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	viewer.repaint();
			
        }
	}

}
